package indi.h.security.encryption.util;

import java.io.IOException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;

public class KeysConvert {

	public static SecretKey symSecretKey(KeySpec keySpec, String encAlgorithm) {
		try {
			SecretKeyFactory instance = SecretKeyFactory.getInstance(encAlgorithm);
			return instance.generateSecret(keySpec);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static SecretKey asymKeyAgrSecretKey(PublicKey puk, PrivateKey prk, String asymAlgorithm,
			String encAlgorithm,AlgorithmParameterSpec algorithmParameterSpec) {
		try {
			KeyAgreement instance = KeyAgreement.getInstance(asymAlgorithm);
			if(algorithmParameterSpec!=null)
				instance.init(prk,algorithmParameterSpec);
			else
				instance.init(prk);
			instance.doPhase(puk, true);
			return instance.generateSecret(encAlgorithm);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} 
		return null;
	}

	public static PublicKey x509Key(byte[] bytes, String asymAlgorithm) {
		try {
			X509EncodedKeySpec xks = new X509EncodedKeySpec(bytes);
			KeyFactory instance = KeyFactory.getInstance(asymAlgorithm);
			return instance.generatePublic(xks);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static PrivateKey pkcs8Key(byte[] bytes, String asymAlgorithm) {
		try {
			PKCS8EncodedKeySpec pks = new PKCS8EncodedKeySpec(bytes);
			KeyFactory instance = KeyFactory.getInstance(asymAlgorithm);
			return instance.generatePrivate(pks);
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static AlgorithmParameters createAlgorithmParameters(String algorithm, byte[] parameter) {
		AlgorithmParameters ap = null;
		try {
			ap = AlgorithmParameters.getInstance(algorithm);
			ap.init(parameter);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ap;
	}

}
